/**
 * 
 */
package core;

import java.util.Set;

/**
 * @author Michael Pitts
 *
 */
public class OptimizedPrePushData extends PrePushData {
	
	private int my_max_height;
	
	public OptimizedPrePushData(SimpleGraph the_graph) {
		super(the_graph, new VertexHeightSet());
		if (my_overflow_nodes.size() > 0) my_max_height = 0;
		else my_max_height = -1;
	}

	@Override public Vertex getExcessNode() {
		return ((VertexHeightSet)my_overflow_nodes).get(my_max_height).iterator().next();
	}
	
	@Override public boolean hasExcessNodes() {
		return my_max_height > -1;
	}
	
	@Override protected NodeData put(final Vertex key, final NodeData value) {
		Set<Vertex> set = ((VertexHeightSet)my_overflow_nodes).get(value.height);
		if (value.excess > 0) {
			if (! set.contains(key)) set.add(key);
		} else {
			if (set.contains(key)) set.remove(key);
			if (set.size() == 0) {
				my_max_height--;
			}
		}
		return super.put(key, value);
	}
	
	@Override public int increaseHeight(final Vertex the_key) {
		final int height = super.increaseHeight(the_key);
		if (my_overflow_nodes.contains(the_key)) {
			((VertexHeightSet)my_overflow_nodes).get(height - 1).remove(the_key);
			((VertexHeightSet)my_overflow_nodes).get(height).add(the_key);
		}
		return height;
	}
}
